/*
 * @Description:
 * @Author: liks
 * @Date: 2025-01-23 14:37:15
 * @LastEditors: liks
 * @LastEditTime: 2025-01-23 15:42:53
 */
import { Injectable, HttpException, HttpStatus } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { UserVisit } from './entities/user-visit.entity';
import { CreateUserVisitDto } from './dto/create-user-visit.dto';
import { PaginationService } from '../../common/pagination/pagination.service';

@Injectable()
export class UserVisitService {
  constructor(
    @InjectRepository(UserVisit)
    private readonly userVisitRepository: Repository<UserVisit>,
    private pageService: PaginationService<UserVisit>,
  ) {
    this.pageService = new PaginationService<UserVisit>(
      this.userVisitRepository,
    );
  }

  async create(createUserVisitDto: CreateUserVisitDto) {
    const newUserVisit = this.userVisitRepository.create(createUserVisitDto);
    return await this.userVisitRepository.save(newUserVisit);
  }

  async findAll() {
    return await this.userVisitRepository.find();
  }

  async pageSearch(params: { page: number; pageSize: number; region: string }) {
    const { page, pageSize, region } = params;
    const qb = this.userVisitRepository.createQueryBuilder('user-visit');
    if (region) {
      qb.andWhere('user-visit.region liks :region', { region: `%${region}%` });
    }
    return this.pageService.pageSearch({ page, pageSize, queryBuilder: qb });
  }

  async findOne(id: string) {
    const visit = await this.userVisitRepository.findOne({ where: { id } });
    if (!visit) throw new HttpException('访问记录不存在', HttpStatus.NOT_FOUND);
    return visit;
  }

  async remove(id: string) {
    const visit = await this.findOne(id);
    return await this.userVisitRepository.remove(visit);
  }
}
